package com.security.config;

import com.security.service.UsersService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UsersService usersService;

    @Bean
    PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usersService).passwordEncoder(getPasswordEncoder());
    }

    @Override
    // 自定义登录页面
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()   //自定义登陆页面
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login")     //登陆访问路径  这里同 action
                .defaultSuccessUrl("/index.html").permitAll()   //登陆成功之后，跳转路径
                .and().exceptionHandling().accessDeniedPage("/403.html")//设置没有权限时跳转到403页面
                .and().authorizeRequests()
                .antMatchers( "/login.html", "/user/login").permitAll()  //设置哪些路径可以直接访问，不需要认证
                .antMatchers("/index.html").hasAuthority("manager1") // 设置当前登录用户访问index.html页面时需要guanwei权限
                // 设置当前登录用户访问1.html页面时需要manager1、manager2、manager3或manager4权限
                .antMatchers("/1.html").hasAnyAuthority("manager2","manager3","manager4")
                .anyRequest().authenticated()   //所有请求都可以访问
                .and().csrf().disable();  //关闭csrf
    }
}
